<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">

          <a-col :md="8" :sm="24">
            <a-form-item label="订单号">
              <a-input v-model="queryParam.orderNumber" placeholder="请输入订单号"/>
            </a-form-item>
          </a-col>

          <a-col :md="5" :sm="24" v-show="$isDev">
            <a-form-item label="订单类型">
              <a-select :default-value="orderType" v-model="queryParam.orderType"
                        style="width: 120px">
                <a-select-option :value="item.id" v-for="(item, index) in orderTypeList">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :md="5" :sm="24" v-show="$isDev">
            <a-form-item label="执行状态">
              <a-select :default-value="executeStatus" v-model="queryParam.executeStatus"
                        style="width: 120px">
                <a-select-option :value="id" v-for="{id, name, code} in executeStatusList">
                  {{ name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :md="!advanced && 4 || 24" :sm="24">
            <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
              <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
              <!--<a-button style="margin-left: 8px" @click="() => queryParam = {}">重置</a-button>-->
            </span>
          </a-col>

        </a-row>
      </a-form>
    </div>

    <div class="table-operator">
      <template v-if="orderType == this.$businessEnum.ORDER_TYPE_ENUM.purchaseOrder.id">
<!--   发货     -->
        <a-button type="primary" @click="$refs.deliverAddForm.add({orderType, orders: selectedRows})" icon="plus">发货</a-button>
      </template>
      <template v-if="viewState == 'productionOrderPool'">
        <a-button type="primary" @click="handleScheduleProductionShow">排单生产</a-button>
        <a-button type="primary" @click="handleRecommendedProduction">推荐生产</a-button>
        <a-button type="primary" @click="handleMaterialCalculation">物料计算</a-button>
        <a-button type="primary" @click="$refs.addForm.add({orderType})" style="float: right;">录入</a-button>
      </template>
    </div>

    <s-table
      ref="table"
      size="default"
      :columns="columnsDynamic"
      :data="loadData"
      :alert="true"
      :rowKey="(record) => record.code"
      :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
    >

      <span slot="status" slot-scope="text, record">
           <a-switch :checked="record.status == 0" :loading="record.loading" @change="onOrderStatusChange($event, record)" />
      </span>

      <span slot="actionProductionPool" slot-scope="text, record">
        <a @click="$refs.editForm.edit(record)">详情</a>
        <a-divider type="vertical"/>
        <a @click="$refs.editForm.edit(record)">订单编辑</a>
        <a-divider type="vertical"/>
        <a @click="$refs.productionMaterialListForm.show(record,
          {title:'产品列表', viewState:'productionPool', materialType: $businessEnum.MATERIAL_TYPE_ENUM.product.id})">
          产品列表</a>
        <a-divider type="vertical"/>
        <a-popconfirm placement="topRight" title="确认删除？" @confirm="() => del(record)">
          <a>删除</a>
        </a-popconfirm>
      </span>

      <span slot="actionInProduction" slot-scope="text, record">
        <a @click="$refs.editForm.edit(record)">详情</a>
        <a-divider type="vertical"/>
        <a @click="$refs.orderMaterialIndexModal.show(record,
          {title:'产品列表', viewState:'inProduction', materialType: $businessEnum.MATERIAL_TYPE_ENUM.product.id})">
          产品列表
        </a>
        <a-divider type="vertical"/>
        <a @click="$refs.productionOrderOutForm.show(record, '包材列表', 'packingOutReadonly')">包材列表</a>
      </span>
    </s-table>

    <add-form ref="addForm" @ok="handleOk"/>
    <edit-form ref="editForm" @ok="handleOk"/>
<!--  生产单产品  -->
    <order-material-index-modal ref="orderMaterialIndexModal" @ok="handleOk"/>
<!--  订单物料列表  -->
    <order-material-form ref="orderMaterialForm" @ok="handleOk"/>
<!--  发货单创建  -->
    <deliver-add-form ref="deliverAddForm" @ok="handleOk"/>
<!--  排单生产提示  -->
    <a-modal title="提示" :visible="scheduleProductionVisible" @ok="handleOkByScheduleProduction" @cancel="scheduleProductionVisible=false">
      <p>确认将选择的生产单进行排单生产吗?</p>
    </a-modal>
<!--  推荐生产  -->
<!--  物料计算  -->
    <material-calculation-form ref="materialCalculationForm" @ok="handleOk"/>
<!--  生产单物料出库  -->
    <production-order-out-form ref="productionOrderOutForm" @ok="handleOk" :readonly="true"/>
<!--  产品完成  -->
    <product-complete-form ref="productCompleteForm" @ok="handleOk"/>
<!--  生产单中物料列表页  -->
    <production-material-list-form ref="productionMaterialListForm" @ok="handleOk"/>
  </a-card>
</template>

<script>
  import {STable} from '@/components'
  import {page, changeStatus, del, doScheduleProduction, doRecommendedProduction, doMaterialCalculation} from '@/api/modular/main/emsorder/emsOrderManage'
  import addForm from './emsOrderAddForm'
  import editForm from './emsOrderEditForm'
  import orderMaterialIndexModal from '@/views/main/emsordermaterial/emsOrderMaterialIndexModal'
  import materialCalculationForm from './emsOrderMaterialCalculationForm'
  import orderMaterialForm from './emsOrderMaterialIndexForm'
  import productionOrderOutForm from '../emsordermaterial/emsOrderMaterialProductionOrderOutForm'
  import deliverAddForm from '../emsordermaterial/deliverOrder/emsDeliverAddForm'
  import productCompleteForm from '../emsordermaterial/emsOrderMaterialProductCompleteForm'
  import productionMaterialListForm from '../emsordermaterial/productionOrder/emsProductionMaterialListForm'
  import { getUrlParam } from '@/utils/util'

  export default {
    components: {
      STable,
      addForm,
      editForm,
      orderMaterialForm,
      deliverAddForm,
      materialCalculationForm,
      productionOrderOutForm,
      productCompleteForm,
      orderMaterialIndexModal,
      productionMaterialListForm,
    },
    data() {
      return {
        advanced: false, // 高级搜索 展开/关闭
        queryParam: {},  // 查询参数
        columns: [
          {
            title: '序号', width:'80px',
            customRender: (text, record, index) => `${index + 1}`
          },
          {
            title: '生产单号',
            dataIndex: 'orderNumber'
          },
          {
            title: '归属子公司',
            dataIndex: 'orgName'
          },
          {
            title: '是否可用',
            dataIndex: 'status',
            scopedSlots: {customRender: 'status'}
          },
          {
            title: '录入时间',
            dataIndex: 'createTime'
          },
          {
            title: '预计完成时间',
            dataIndex: ''
          },
          {
            title: '操作',
            dataIndex: 'action',
            width: '280px',
            scopedSlots: {customRender: 'actionProductionPool'}
          }
        ],
        columnsInProduction: [
          {
            title: '序号', width:'80px',
            customRender: (text, record, index) => `${index + 1}`
          },
          {
            title: '生产单号',
            dataIndex: 'orderNumber'
          },
          {
            title: '归属子公司',
            dataIndex: 'orgName'
          },
          {
            title: '录入时间',
            dataIndex: 'createTime'
          },
          {
            title: '排单时间',
            dataIndex: ''
          },
          {
            title: '操作',
            dataIndex: 'action',
            width: '250px',
            scopedSlots: {customRender: 'actionInProduction'}
          }
        ],
        // 加载数据方法 必须为 Promise 对象
        loadData: parameter => {
          // let ot = this.orderType
          return page(Object.assign(parameter, this.queryParam)).then((res) => {
            return res.data
          })
        },
        scheduleProductionVisible: false,
        selectedRowKeys: [],
        selectedRows: [],
        defaultExpandedKeys: [],
        replaceFields: {
          key: 'id',
        },
        urlParam: {},
        columnsType: '',
        viewState: '',
      }
    },
    watch: {
      '$route.path': function (newValue) {
        let urlParam = getUrlParam(this.$route.path)
        this.setUrlParam(urlParam)

        setTimeout(() => {
          this.$refs.table.refresh(true)
          this.$refs.table.clearSelected()
        }, 100)
      }
    },
    computed: {
      orderType() {
        return this.urlParam.orderType
      },
      orderTypeList() {
        let result = []
        result.push({id: '', name: '全部', code: 'all'})
        for (const key in this.$businessEnum.ORDER_TYPE_ENUM) {
          let value = this.$businessEnum.ORDER_TYPE_ENUM[key]
          result.push(value)
        }
        return result
      },
      executeStatus() {
        return this.urlParam.executeStatus
      },
      executeStatusList() {
        let result = []
        result.push({id: '', name: '全部', code: 'all'})
        for (const key in this.$businessEnum.EXECUTE_STATUS_ENUM) {
          let value = this.$businessEnum.EXECUTE_STATUS_ENUM[key]
          result.push(value)
        }
        return result
      },
      columnsDynamic() {
        if (this.columnsType == 'ProductionCenter-ProductionPool' || this.columnsType == '' || !this.columnsType) {
          return this.columns
        } else if (this.columnsType == 'ProductionCenter-InProduction') {
          return this.columnsInProduction
        } else {
          return []
        }
      },
    },
    created() {
      let urlParam = getUrlParam(this.$route.path)
      this.setUrlParam(urlParam)
    },
    methods: {
      setUrlParam(urlParam) {
        this.urlParam = urlParam
        let {orderType, executeStatus, columnsType, viewState} = urlParam
        this.columnsType = columnsType
        this.viewState = viewState || ''
        this.queryParam = {orderType: orderType||'', executeStatus: executeStatus || ''}
      },
      del(record) {
        del(record).then((res) => {
          if (res.success) {
            this.$message.success('删除成功')
            this.$refs.table.refresh()
          } else {
            this.$message.error('删除失败：' + res.message)
          }
        }).catch((err) => {
          this.$message.error('删除错误：' + err.message)
        })
      },
      toggleAdvanced() {
        this.advanced = !this.advanced
      },
      handleOk() {
        this.$refs.table.refresh()
      },
      onSelectChange(selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows = selectedRows
      },
      onOrderStatusChange(checked, row) {
        row.loading = true
        let {orderId} = row
        let status = checked ? 0 : 1
        let parameter = {orderId, status}
        changeStatus(parameter).then(res => {
          this.handleOk()
        })
      },
      // 排单生产
      handleScheduleProductionShow() {
        if (this.validateScheduleProduction()) {
          this.scheduleProductionVisible = true
        }
      },
      validateScheduleProduction() {
        let selectedRows = this.selectedRows
        if (selectedRows.length == 0) {
          this.$message.error('请先选择要排单生产的订单')
          return false
        }
        let unavailableOrders = selectedRows.filter(value => value.status != 0)
        if (unavailableOrders.length > 0) {
          this.$message.error('订单状态必须为"可用"才可以进行排单')
          return false
        }
        return true
      },
      handleOkByScheduleProduction() {
        // 调接口,排单生产
        if (this.validateScheduleProduction()) {
          let orderIds = this.selectedRows.map(value => value.orderId).join(',')
          doScheduleProduction({orderIds}).then(res => {
            this.$message.success(res.message)
          })
        }
      },
      handleRecommendedProduction() {

      },
      handleMaterialCalculation() {
        // 物料计算
        let orderIds = this.selectedRows.map(row => row.orderId).join(',')
        this.$refs.materialCalculationForm.add(orderIds)
        // doMaterialCalculation({orderIds: selectedRowKeys}).then((res) => {
        //   let data = res.data
        //
        // })
      }
    }
  }
</script>

<style lang="less">
.table-operator {
  margin-bottom: 18px;
}
button {
  margin-right: 8px;
}
</style>
